#include "server.h"

using namespace easyWebServer;
using namespace dxy::event;
using namespace dxy::threadPool;
using namespace std;

namespace dxy::easyWebServer
{

void taskfunc(std::shared_ptr<Task> t)
{
    t->run();
}

void quitCallBack(int sig)
{
    slt(DxyThreadPool).stop();
    // slt(ThreadPool).stop();
    vector<string> nodes = RosNodeManager::getInstance().getAllNode();
    for(int i = 0; i < nodes.size(); i++)
    {
        info("node %s quit...", nodes[i].c_str());
        RosNodeManager::getInstance().killNode(nodes[i], true);
    }
    info("server quit");
    exit(-1);
}

Server::Server()
{

}

Server::~Server()
{

}




void Server::init()
{

    signal(SIGINT, quitCallBack);

    // sigset_t sigsets;
    // sigemptyset(&sigsets);
    // sigaddset(&sigsets, SIGINT);
    // sigprocmask(SIG_BLOCK, &sigsets, NULL);
    // int sigfd = signalfd(-1, &sigsets, 0);


    slt(DxyThreadPool).start(slt(Json)["threadPoolNumber"].asInt());

    // slt(ThreadPool).init(2);

    slt(DxySocket).init(slt(Json)["host"].asString(), slt(Json)["port"].asInt());

    info("server start");
    
}

void Server::start()
{   
    // slt(DxyEvent).eventDispatch();
 
    while (1)
    {
        int clifd = slt(DxySocket).socketAccept();
        // setNoBlock(clifd);
        auto task = make_shared<Task>(clifd);
        // slt(ThreadPool).commit(taskfunc, task);
        slt(DxyThreadPool).addTask(taskfunc, task);
    }
    
}



}

